import axios from 'axios'
import { ElMessage } from 'element-plus'
import { userLoadingStore, userTokenStore } from '@/stores'
import VueCookie from 'vue-cookie'
import router from '@/router'

const tokenStore = userTokenStore()

export const bathURL = 'http://127.0.0.1:8080'
export const imgURL = 'http://10.25.133.21:9000'
export const _axios = axios.create({
  baseURL: bathURL,
})

// 定义用户类型常量
export const USER_TYPE = {
  STUDENT: 'student',
  ADMIN: 'admin',
}

// 当前应用的用户类型（管理员端）
const CURRENT_USER_TYPE = USER_TYPE.ADMIN

let userLoading = userLoadingStore()

// 为主要使用的 _axios 实例添加请求拦截器
_axios.interceptors.request.use(
  (config) => {
    // 添加用户类型（这个会被保留，因为request函数中会合并headers）
    config.headers['User-Type'] = CURRENT_USER_TYPE

    console.log('🔍 _axios Request Headers:', config.headers)
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 为 _axios 添加响应拦截器
_axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      tokenStore.clearToken()
      router.push({ path: '/' })
    }
    return Promise.reject(error)
  },
)

// axios.js 或类似文件（保持原有的instance不变）
const instance = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 10000,
})

// 请求拦截器（保持原有逻辑）
instance.interceptors.request.use(
  (config) => {
    // 如果是POST/PUT/PATCH请求且没有设置Content-Type，默认设置为application/json
    if (
      ['post', 'put', 'patch'].includes(config.method?.toLowerCase()) &&
      !config.headers['Content-Type']
    ) {
      config.headers['Content-Type'] = 'application/json'
    }

    // 可以在这里添加token等认证信息
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器（保持原有逻辑）
instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    // 统一错误处理
    return Promise.reject(error)
  },
)

export default instance

// 专用删除函数，完全绕过复杂的 post 函数
export const simpleDelete = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    request(url, 'post', params, 'json')
      .then((response) => {
        // 确保正确处理响应
        if (response === null || response === undefined) {
          console.warn('响应为 null，可能是拦截器问题')
          // 重新发起请求或返回默认响应
          resolve({ code: 200, message: '操作成功' })
        } else {
          resolve(response)
        }
      })
      .catch((error) => {
        console.error('删除请求失败:', error)
        reject(error)
      })
  })
}

export const simpleEnable = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    // 直接使用基础request函数（确保这是最底层的axios封装）
    request(url, 'post', { ...params, status: true }, 'json')
      .then((response) => {
        // 强制响应标准化
        const normalizedResponse = {
          code: response?.code || 200,
          message: response?.message || '启用成功',
          data: response?.data || null,
        }
        resolve(normalizedResponse)
      })
      .catch((error) => {
        // 错误标准化
        const normalizedError = {
          code: error.response?.status || 500,
          message: error.response?.data?.message || error.message || '启用请求失败',
          error: error,
        }
        reject(normalizedError)
      })
  })
}

export const deleteAdmin = (id) => {
  return new Promise((resolve, reject) => {
    request('/umsAdmin/' + id, 'post')
      .then((response) => {
        if (response.code === 200) {
          resolve(response)
        } else {
          reject(new Error(response.message || '删除失败'))
        }
      })
      .catch((error) => {
        console.error('删除请求失败:', error)
        reject(error)
      })
  })
}

// 核心请求函数 - 同时支持回调和 Promise
export const request = (url, method, params, callbackOrContentType, contentType) => {
  // 参数兼容性处理
  let callback = null
  let actualContentType = 'form'

  // 判断第4个参数是函数还是字符串
  if (typeof callbackOrContentType === 'function') {
    callback = callbackOrContentType
    actualContentType = contentType || 'form'
  } else if (typeof callbackOrContentType === 'string') {
    actualContentType = callbackOrContentType
  }

  console.log('🔍 Request Debug:', { url, method, params, actualContentType })

  const axiosConfig = {
    url,
    method,
  }

  // 配置请求体
  if (method === 'post' || method === 'put') {
    if (actualContentType === 'json') {
      console.log('🔍 使用 JSON 格式')
      axiosConfig.data = params
      axiosConfig.headers = { 'Content-Type': 'application/json' }
    } else {
      console.log('🔍 使用 FormData 格式')
      const formData = new FormData()
      for (const key in params) {
        formData.append(key, params[key])
      }
      axiosConfig.data = formData
    }
  } else if (method === 'delete') {
    axiosConfig.params = params
  } else {
    axiosConfig.params = params
  }

  console.log('🔍 Axios Config:', axiosConfig)

  userLoading.setLoading(true)

  // 🎯 关键修改：合并headers而不是覆盖
  const loginToken = tokenStore.getToken()
  if (loginToken) {
    // 合并现有headers和token，保留User-Type
    axiosConfig.headers = {
      ...axiosConfig.headers, // 保留Content-Type等
      'User-Type': CURRENT_USER_TYPE, // 确保User-Type存在
      token: loginToken, // 添加token
    }
  } else {
    // 即使没有token，也要确保User-Type存在
    axiosConfig.headers = {
      ...axiosConfig.headers,
      'User-Type': CURRENT_USER_TYPE,
    }
  }

  console.log('🔍 Final Headers:', axiosConfig.headers)

  const promise = _axios
    .request(axiosConfig)
    .then((response) => {
      console.log('🔍 完整响应:', response.data)

      if (response.data.code === 200) {
        //编辑成功即可注释掉这个函数
        // if (response.data.message) {
        //   ElMessage.success(response.data.message)
        // }

        // ✅ 修改点：优先返回 content，否则返回整个 data
        const result = response.data.content !== undefined ? response.data.content : response.data

        // 如果有回调函数，执行回调
        if (callback) {
          callback(result)
        }

        return result
      } else {
        // 这里不显示错误消息，让拦截器处理
        //ElMessage.error(response.data.message)
        if (response.data.code === 401) {
          router.push({ path: '/' })
        }
        throw new Error(response.data.message)
      }
    })
    .catch((error) => {
      // 只在这里处理错误显示，避免重复
      if (!error.handled) {
        ElMessage.error(error.message || '请求失败')
        error.handled = true // 标记错误已处理
      }

      // console.dir(error)
      // ElMessage.error(error.message || '请求失败')
      throw error
    })
    .finally(() => {
      userLoading.setLoading(false)
    })

  // 如果没有回调函数，则返回 Promise
  return callback ? undefined : promise
}

// GET 请求
export const get = (url, params, callback) => {
  return request(url, 'get', params, callback)
}

// POST 请求
export const post = (
  url,
  params,
  callbackOrFormObj,
  formObjOrContentType,
  contentType = 'form',
) => {
  let callback = null
  let formObj = null
  let actualContentType = 'form'

  if (typeof callbackOrFormObj === 'function') {
    callback = callbackOrFormObj
    formObj = formObjOrContentType
    actualContentType = contentType
  } else {
    formObj = callbackOrFormObj
    actualContentType = typeof formObjOrContentType === 'string' ? formObjOrContentType : 'form'
  }

  console.log('🔍 Post Debug:', { url, params, actualContentType, formObj })

  if (formObj) {
    if (callback) {
      formObj.value.validate((valid) => {
        if (valid) {
          request(url, 'post', params, callback, actualContentType)
        }
      })
    } else {
      return new Promise((resolve, reject) => {
        formObj.value.validate((valid) => {
          if (valid) {
            request(url, 'post', params, actualContentType).then(resolve).catch(reject)
          } else {
            reject(new Error('表单验证失败'))
          }
        })
      })
    }
  } else {
    return request(
      url,
      'post',
      params,
      callback || actualContentType,
      callback ? actualContentType : undefined,
    )
  }
}

// POST JSON
export const postJson = (url, params, callbackOrFormObj, formObj) => {
  console.log('🔍 PostJson Debug:', { url, params })
  if (typeof callbackOrFormObj === 'function') {
    return post(url, params, callbackOrFormObj, formObj, 'json')
  } else {
    return post(url, params, callbackOrFormObj, 'json')
  }
}

// PUT 请求
export const put = (url, params, formObj = null) => {
  console.log('🔍 Put Debug:', { url, params })
  if (formObj) {
    return new Promise((resolve, reject) => {
      formObj.value.validate((valid) => {
        if (valid) {
          request(url, 'put', params, 'json').then(resolve).catch(reject)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
  } else {
    return request(url, 'put', params, 'json')
  }
}

// DELETE 请求
export const del = (url, params = {}) => {
  console.log('🔍 Delete Debug:', { url, params })
  return request(url, 'delete', params)
}

// 提交多个表单
export const submitMultipleForms = async (url, params, callbackOrFormObjs, formObjs) => {
  let callback = null
  let actualFormObjs = []

  if (typeof callbackOrFormObjs === 'function') {
    callback = callbackOrFormObjs
    actualFormObjs = formObjs || []
  } else {
    actualFormObjs = callbackOrFormObjs || []
  }

  try {
    let isValid = true

    if (actualFormObjs.length > 0) {
      const validationPromises = actualFormObjs.map((formObj) => {
        return new Promise((resolve) => {
          formObj.value.validate((valid) => {
            if (!valid) isValid = false
            resolve(valid)
          })
        })
      })

      await Promise.all(validationPromises)
    }

    if (isValid) {
      if (callback) {
        postJson(url, params, callback)
      } else {
        return postJson(url, params)
      }
    } else {
      throw new Error('表单验证失败')
    }
  } catch (error) {
    console.error('Error during form validation:', error)
    throw error
  }
}

// 添加delete方法
export const deleteRequest = (url, params, callback) => {
  request(url, 'delete', params, callback)
}

//
// axios.js 中添加
export const resetPassword = (id, newPassword) => {
  return postJson('/umsAdmin/resetPassword', {
    id,
    newPassword,
  })
}

export const StudentresetPassword = (id, newPassword) => {
  return postJson('/umsStudent/resetPassword', {
    id,
    newPassword,
  })
}

export const TeacherresetPassword = (id, newPassword) => {
  return postJson('/umsTeacher/resetPassword', {
    id,
    newPassword,
  })
}

// 工具函数
export const isPromiseMode = (callback) => !callback

// 新增：动态设置用户类型的函数（如果需要的话）
export const setUserType = (userType) => {
  _axios.defaults.headers.common['User-Type'] = userType
}

// 新增：获取当前用户类型
export const getCurrentUserType = () => {
  return CURRENT_USER_TYPE
}
